

#include "log.hpp"
#include "comm.hpp"

using namespace std;

int main()
{
    Init init;

    int shmid = shmCreater();

    // cout << shmid << endl;
    // shmat的第二个参数传入的是你想将共享内存的映射放在虚拟地址空间的哪个地方
    // 第三个参数传入控制该进程是只读或者刻度可写
    char *shmem = (char *)shmat(shmid, nullptr, 0);
    if (shmem == (char *)-1)
    {
        getLog().send_message(Fatal, "shmat fail:%s", strerror(errno));
        exit(3);
    }
    getLog().send_message(Info, "shmat success");

    int fd = open(fifo_name, O_RDONLY);
    if (fd == -1)
    {
        getLog().send_message(Fatal, "open fifo error!\n");
        // perror("open fifo");
        exit(FIFO_OPEN_ERR);
    }
    getLog().send_message(Info, "serve open fifo_file excuess!\n");

    // 共享内存并没有同步互斥功能，可以利用管道来做到这一点
    while (true)
    {
        char c;
        ssize_t num = read(fd, &c, sizeof c);
        if(num > 0) cout << "processa get mesg:" << shmem << endl;
        else break;
        sleep(1);
    }
    close(fd);
    int m = shmdt((void *)shmem);
    if (m == -1)
    {
        getLog().send_message(Fatal, "shm unlink fail:%s", strerror(errno));
        exit(5);
    }
    getLog().send_message(Info, "shm unlink success!");
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n == -1)
    {
        getLog().send_message(Fatal, "shm delte fail:%s", strerror(errno));
        exit(4);
    }
    getLog().send_message(Info, "shm delete success!");
    return 0;
}